<template>
  <div class="roles-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <el-icon class="title-icon"><Key /></el-icon>
          角色管理
        </h1>
        <p class="page-description">查看系统角色信息和权限配置</p>
      </div>
    </div>

    <!-- 角色统计 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="8" v-for="stat in roleStats" :key="stat.role">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon :size="32" :color="stat.role === 'admin' ? '#f56565' : '#4299e1'">
                  <User v-if="stat.role === 'user'" />
                  <UserFilled v-else />
                </el-icon>
              </div>
              <div class="stat-info">
                <h3 class="stat-title">{{ stat.displayName }}</h3>
                <p class="stat-count">{{ stat.count }} 人</p>
                <p class="stat-permissions">{{ stat.permissions.length }} 个权限</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover" class="stat-card total-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon :size="32" color="#10b981">
                  <DataAnalysis />
                </el-icon>
              </div>
              <div class="stat-info">
                <h3 class="stat-title">总用户数</h3>
                <p class="stat-count">{{ totalUsers }} 人</p>
                <p class="stat-permissions">{{ availableRoles.length }} 个角色</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 角色详情 -->
    <div class="roles-section">
      <el-card shadow="never" class="roles-card">
        <template #header>
          <div class="card-header">
            <h2>角色详情</h2>
            <el-button @click="refreshData" :icon="Refresh" circle />
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :span="12" v-for="role in availableRoles" :key="role.value">
            <el-card shadow="hover" class="role-detail-card">
              <template #header>
                <div class="role-header">
                  <el-tag 
                    :type="role.value === 'admin' ? 'danger' : 'primary'" 
                    size="large"
                    class="role-tag"
                  >
                    {{ role.displayName }}
                  </el-tag>
                  <el-button
                    @click="viewRoleUsers(role.value)"
                    type="primary"
                    size="small"
                    link
                  >
                    查看用户
                  </el-button>
                </div>
              </template>

              <div class="permissions-section">
                <h4 class="permissions-title">权限列表</h4>
                <div class="permissions-list">
                  <el-tag
                    v-for="permission in role.permissions"
                    :key="permission"
                    class="permission-tag"
                    size="small"
                  >
                    {{ formatPermission(permission) }}
                  </el-tag>
                </div>
              </div>

              <div class="role-actions">
                <el-button
                  @click="checkPermission(role.value)"
                  :icon="Search"
                  size="small"
                >
                  权限检查
                </el-button>
                <el-button
                  @click="compareRoles(role.value)"
                  :icon="DataAnalysis"
                  size="small"
                  v-if="role.value !== 'admin'"
                >
                  与管理员对比
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- 角色用户列表对话框 -->
    <el-dialog
      v-model="showUsersDialog"
      :title="`${selectedRoleDisplayName} - 用户列表`"
      width="800px"
    >
      <el-table :data="roleUsers" v-loading="loadingUsers">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="createdAt" label="创建时间">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 权限检查对话框 -->
    <el-dialog
      v-model="showPermissionDialog"
      title="权限检查"
      width="600px"
    >
      <el-form :model="permissionForm" label-width="100px">
        <el-form-item label="用户ID">
          <el-input v-model="permissionForm.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="权限">
          <el-select v-model="permissionForm.permission" placeholder="选择要检查的权限">
            <el-option
              v-for="permission in allPermissions"
              :key="permission"
              :label="formatPermission(permission)"
              :value="permission"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="doCheckPermission" type="primary" :loading="checkingPermission">
            检查权限
          </el-button>
        </el-form-item>
      </el-form>

      <div v-if="permissionResult" class="permission-result">
        <el-alert
          :title="permissionResult.hasPermission ? '有权限' : '无权限'"
          :type="permissionResult.hasPermission ? 'success' : 'error'"
          :description="`用户 ${permissionResult.username} (${permissionResult.roleDisplayName}) ${permissionResult.hasPermission ? '拥有' : '没有'} ${formatPermission(permissionResult.permission)} 权限`"
          show-icon
        />
      </div>
    </el-dialog>

    <!-- 角色对比对话框 -->
    <el-dialog
      v-model="showCompareDialog"
      title="角色权限对比"
      width="700px"
    >
      <div v-if="compareResult" class="compare-result">
        <el-row :gutter="20">
          <el-col :span="12">
            <h4>{{ compareResult.role1.displayName }}</h4>
            <div class="permissions-list">
              <el-tag
                v-for="permission in compareResult.role1.permissions"
                :key="permission"
                size="small"
                class="permission-tag"
              >
                {{ formatPermission(permission) }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="12">
            <h4>{{ compareResult.role2.displayName }}</h4>
            <div class="permissions-list">
              <el-tag
                v-for="permission in compareResult.role2.permissions"
                :key="permission"
                size="small"
                class="permission-tag"
              >
                {{ formatPermission(permission) }}
              </el-tag>
            </div>
          </el-col>
        </el-row>
        <el-divider />
        <el-alert
          :title="compareResult.result"
          type="info"
          show-icon
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Key, 
  User, 
  UserFilled, 
  DataAnalysis, 
  Refresh, 
  Search 
} from '@element-plus/icons-vue'
import { 
  getAllRoles, 
  getRoleStats, 
  getUsersByRole, 
  checkUserPermission, 
  compareRoles 
} from '@/api/roles'
import type { 
  IRoleInfo, 
  IRoleStats, 
  IUserResponse, 
  UserRole 
} from '@/types'

// 响应式数据
const availableRoles = ref<IRoleInfo[]>([])
const roleStats = ref<IRoleStats[]>([])
const totalUsers = ref(0)
const loading = ref(false)

// 用户列表对话框
const showUsersDialog = ref(false)
const roleUsers = ref<IUserResponse[]>([])
const loadingUsers = ref(false)
const selectedRoleDisplayName = ref('')

// 权限检查对话框
const showPermissionDialog = ref(false)
const checkingPermission = ref(false)
const permissionForm = reactive({
  userId: '',
  permission: ''
})
const permissionResult = ref<any>(null)

// 角色对比对话框
const showCompareDialog = ref(false)
const compareResult = ref<any>(null)

// 计算所有权限
const allPermissions = computed(() => {
  const permissions = new Set<string>()
  availableRoles.value.forEach(role => {
    role.permissions.forEach(permission => {
      permissions.add(permission)
    })
  })
  return Array.from(permissions)
})

// 获取角色列表
const fetchRoles = async () => {
  try {
    const response = await getAllRoles()
    if (response.success) {
      availableRoles.value = response.data.roles
    }
  } catch (error: any) {
    ElMessage.error('获取角色列表失败')
  }
}

// 获取角色统计
const fetchRoleStats = async () => {
  try {
    const response = await getRoleStats()
    if (response.success) {
      roleStats.value = response.data.statistics
      totalUsers.value = response.data.totalUsers
    }
  } catch (error: any) {
    ElMessage.error('获取角色统计失败')
  }
}

// 查看角色用户
const viewRoleUsers = async (role: UserRole) => {
  loadingUsers.value = true
  showUsersDialog.value = true
  selectedRoleDisplayName.value = availableRoles.value.find(r => r.value === role)?.displayName || ''
  
  try {
    const response = await getUsersByRole(role)
    if (response.success) {
      roleUsers.value = response.data.users
    }
  } catch (error: any) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loadingUsers.value = false
  }
}

// 权限检查
const checkPermission = (role: UserRole) => {
  permissionForm.userId = ''
  permissionForm.permission = ''
  permissionResult.value = null
  showPermissionDialog.value = true
}

const doCheckPermission = async () => {
  if (!permissionForm.userId || !permissionForm.permission) {
    ElMessage.warning('请填写用户ID和权限')
    return
  }
  
  checkingPermission.value = true
  try {
    const response = await checkUserPermission(permissionForm.userId, permissionForm.permission)
    if (response.success) {
      permissionResult.value = response.data
    }
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '权限检查失败')
  } finally {
    checkingPermission.value = false
  }
}

// 角色对比
const compareRoles = async (role: UserRole) => {
  try {
    const response = await compareRoles(role, 'admin' as UserRole)
    if (response.success) {
      compareResult.value = response.data
      showCompareDialog.value = true
    }
  } catch (error: any) {
    ElMessage.error('角色对比失败')
  }
}

// 刷新数据
const refreshData = async () => {
  loading.value = true
  try {
    await Promise.all([fetchRoles(), fetchRoleStats()])
  } finally {
    loading.value = false
  }
}

// 格式化权限名称
const formatPermission = (permission: string) => {
  const permissionMap: Record<string, string> = {
    'user:read': '查看用户',
    'user:create': '创建用户',
    'user:update': '更新用户',
    'user:delete': '删除用户',
    'admin:manage': '管理员权限'
  }
  return permissionMap[permission] || permission
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 组件挂载时获取数据
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.roles-container {
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.header-content h1.page-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.title-icon {
  margin-right: 12px;
  color: #667eea;
}

.page-description {
  color: #6b7280;
  margin: 0;
  font-size: 14px;
}

.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  flex-shrink: 0;
}

.stat-info h3.stat-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #374151;
}

.stat-count {
  margin: 0 0 4px 0;
  font-size: 24px;
  font-weight: 700;
  color: #1f2937;
}

.stat-permissions {
  margin: 0;
  font-size: 12px;
  color: #6b7280;
}

.roles-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #374151;
}

.role-detail-card {
  margin-bottom: 16px;
  border-radius: 8px;
  border: none;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.role-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.role-tag {
  font-weight: 600;
}

.permissions-section {
  margin-bottom: 16px;
}

.permissions-title {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.permissions-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.permission-tag {
  margin: 0;
}

.role-actions {
  display: flex;
  gap: 8px;
}

.permission-result {
  margin-top: 20px;
}

.compare-result h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #374151;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-dialog__header) {
  padding: 20px 20px 10px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>
